import { createRouter, createWebHistory } from 'vue-router';
import Home from '@/components/HelloWorld.vue'; // 首页组件
import Register from '@/views/Register.vue'; // 注册页面组件
import Login from '@/views/Login.vue'; // 登录页
import Article_Release from '@/views/Article_Release.vue';
import Article_management from '@/views/Article_management.vue';
import User_management from '@/views/User_management.vue';
import EditArticle from '@/views/EditArticle.vue';
import ArticleDetail from '@/views/ArticleDetail.vue'; // 引入查看文章详情的页面
import UserManagement from '@/views/User_management.vue';
import EditUser from '@/views/EditUsers.vue';
import erjifenlei from '@/views/erjifenlei.vue';



import { isLoggedIn } from '@/utils/auth';  // 导入判断登录状态的函数
import Favorite_management from '@/views/Favorite_management.vue';

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home, // 首页组件
      // 需要登录才能访问
  },
  {
    path: '/register',
    name: 'Register',
    component: Register, // 注册页面组件
  },
  {
    path: '/login',
    name: 'Login',
    component: Login, // 登录页面
  },
  {
    path: '/Article_Release',
    name: 'Article_Release',
    component: Article_Release,
    meta: { requiresAuth: true }
  },
  {
    path: '/Article_management',
    name: 'Article_management',
    component: Article_management,
    meta: { requiresAuth: true }
  },
  {
    path: '/User_management',
    name: 'User_management',
    component: User_management,
    meta: { requiresAuth: true }
  },
  {
    path: '/Favorite_management',
    name: 'Favorite_management',
    component: Favorite_management,
    meta: { requiresAuth: true }
  },
  {
    path: '/article/edit/:id',
    name: 'EditArticle',
    component: EditArticle
  },
  {
    path: '/article/detail/:id',
    name: 'ArticleDetail',
    component: ArticleDetail, // 显示文章详情
  },
    {
    path: "/user_management",
    name: "UserManagement",
    component: UserManagement,
  },
  {
    path: "/users/edit/:id",
    name: "EditUser",
    component: EditUser,
    props: true, // 允许路由参数作为组件的 props
  },
  {
    path: '/erjifenlei',
    name: 'erjifenlei',
    component: erjifenlei
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});
// 设置全局路由守卫
router.beforeEach((to, from, next) => {
    if (to.meta.requiresAuth && !isLoggedIn()) {
      // 如果目标路由需要登录且用户没有登录，重定向到登录页面
      next({ name: 'Login' });
    } else {
      next();
    }
  });
export default router;
